package org.example.ssmDemo.task;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.RecursiveAction;
import org.apache.logging.log4j.util.Strings;
import org.example.ssmDemo.entity.DoctorEntity;
import org.example.ssmDemo.entity.DoctorHaoEntity;
import org.example.ssmDemo.service.DoctorInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @version v1.0
 * @Description: 医生信息刷新
 * @Author: cliang.liangchao
 * @Date: 2021/3/4 11:27
 */
public class DoctorDealAction extends RecursiveAction {
	// 任务数阈值
	private static final int MAX_TASK_NUM = 4;

	private final static Logger LOGGER = LoggerFactory.getLogger(DoctorDealAction.class);

	private int start;

	private int end;

	private List<DoctorEntity> doctorEntityList;

	private DoctorInfoService doctorInfoService;

	public DoctorDealAction(List<DoctorEntity> doctorEntityList, DoctorInfoService doctorInfoService, int start, int end) {
		this.doctorEntityList = doctorEntityList;
		this.doctorInfoService = doctorInfoService;
		this.start = start;
		this.end = end;
	}

	@Override
	protected void compute() {

		if ((end - start) < MAX_TASK_NUM) {
			for (int i = start; i < end; i++) {
				updateDoctorInfo(doctorEntityList.get(i));
			}
		} else {
			// 使用二分法分配任务
			int inter = (start + end) / 2;
			DoctorDealAction left = new DoctorDealAction(doctorEntityList, doctorInfoService, start, inter);
			DoctorDealAction right = new DoctorDealAction(doctorEntityList, doctorInfoService, inter, end);
			// 并行执行两个小任务
			invokeAll(left, right);
		}
	}


	/**
	 * 查询和刷新医生职称信息
	 * @param doctorEntity 医生信息
	 */
	public void updateDoctorInfo(DoctorEntity doctorEntity) {
		// 医生姓名
		String doctorName = doctorEntity.getDoctorName();

		// 所在医院
		List<String> hospNameList = new ArrayList<>();

		if (Strings.isNotEmpty(doctorEntity.getHospital())) {
			hospNameList = new ArrayList<>(Arrays.asList(doctorEntity.getHospital().split("/")));
		}


		for(String hospName: hospNameList) {
			// 根据标准去别名表查询医院别名
			List<String> aliasList = doctorInfoService.queryHospAlias(hospName);

			// 根据医生名、所在医院名(或别名)去好大夫医生表（doctor_hdf）查询职称信息
			List<DoctorHaoEntity> doctorHaoEntities = doctorInfoService.queryDoctorInHaoDaiFu(doctorName, hospName, aliasList);

			// 同一医院下仅存在唯一姓名的医生
			if (doctorHaoEntities.size() == 1) {
				String clinicalTile = doctorHaoEntities.get(0).getRank();
				String departType = doctorHaoEntities.get(0).getDepartmentType();
				String department = doctorHaoEntities.get(0).getDepartmentName();
				doctorEntity.setClinicalTile(clinicalTile);
				doctorEntity.setDepartType(departType);
				doctorEntity.setDepartment(department);
				// 更新该医生信息
				doctorInfoService.updateClinicalTile(doctorEntity);
				break;
			}
		}
	}
}
